package distance;

import org.junit.Test;

import java.util.List;

public class Test2
{
    public Double determinant(double v1, double v2, double v3, double v4)
    {
        return (v1 * v4 - v2 * v3);
    }

    public Boolean intersect(String p1, String p2, String p3, String p4)
    {
        String[] p1s = p1.split(",");
        String[] p2s = p2.split(",");
        String[] p3s = p3.split(",");
        String[] p4s = p4.split(",");
        //线1的起点
        double x1 = Double.valueOf(p1s[0]);
        double y1 = Double.valueOf(p1s[1]);

        //线1的终点
        double x2 = Double.valueOf(p2s[0]);
        double y2 = Double.valueOf(p2s[1]);

        //线2的起点
        double x3 = Double.valueOf(p3s[0]);
        double y3 = Double.valueOf(p3s[1]);

        //线2的终点
        double x4 = Double.valueOf(p4s[0]);
        double y4 = Double.valueOf(p4s[1]);

        Double determinant = determinant(x2 - x1, x3 - x4, y2 - y1, y3 - y4);

        if (determinant <= (1e-6) && determinant >= -(1e-6))
        {
            return false;
        }

        Double namenda = determinant(x3 - x1, x3 - x4, y3 - y1, y3 - y4)/determinant;

        if (namenda > 1 || namenda < 0)
        {
            return false;
        }

        Double miu = determinant(x2 - x1, x3 - x1, y2 - y1, y3 - y1)/determinant;
        if (miu > 1 || miu < 0)
        {
            return false;
        }
        return true;

    }

    @Test
    public void test()
    {
        Boolean aBoolean = intersect("112.8481,28.2903", "112.8904,28.3044", "112.8567,28.3082", "112.8713,28.2838");
        System.out.println(aBoolean);
    }

    /*
     * p为待测点  list为多边形边界
     */
    private static String rayCasting(Point2d p, List<Point2d> list) {
        double px = p.x, py = p.y;
        boolean flag = false;
        //
        for (int i = 0, l = list.size(), j = l - 1; i < l; j = i, i++) {
            //取出边界的相邻两个点
            double sx = list.get(i).x,
                   sy = list.get(i).y,
                   tx = list.get(j).x,
                   ty = list.get(j).y;
            // 点与多边形顶点重合
            if ((sx == px && sy == py) || (tx == px && ty == py)) {
                return "on";
            }
            // 判断线段两端点是否在射线两侧
            // 思路:作p点平行于y轴的射线 作s,t的平行线直线  如果射线穿过线段，则py的值在sy和ty之间
            if ((sy < py && ty >= py) || (sy >= py && ty < py)) {
                // 线段上与射线 Y 坐标相同的点的 X 坐标 ,即求射线与线段的交点
                double x = sx + (py - sy) * (tx - sx) / (ty - sy);
                // 点在多边形的边上
                if (x == px) {
                    return "on";
                }
                // 射线穿过多边形的边界
                if (x > px) {
                    flag = !flag;
                }
            }
        }
        // 射线穿过多边形边界的次数为奇数时点在多边形内
        return flag ? "in" : "out";
    }

}
